import { login, setTimeEnglish, getInfo } from "@/api/index";
// import { getInfo } from "../../api/student";
import { updateLeave } from "../../api/game";
import { getToken, setToken, removeToken, localstorageGetToken, localstorageSetToken, localstorageRemoveToken } from "@/utils/auth";
import router from "../../router";
console.log(this);
const user = {
  state: {
    token: getToken() || localstorageGetToken(), //用户Token
    userInfo: {}, //用户信息
    startTime: null,
    //1英式，0美式
    isBritish: 1,
    baseIP: "192.168.119.110",
    startTimeGame: null,
    tabSelectStatus: 1
  },

  mutations: {
    setTabsStatus(state, status) {
      state.tabSelectStatus = status;
    },
    SET_TOKEN: (state, token) => {
      //给Token赋值
      state.token = token;
    },
    SET_USERINFO: (state, userInfo) => {
      //用户信息赋值
      if (userInfo.logo) {
        state.userInfo = userInfo;
      } else {
        state.userInfo = Object.assign({}, userInfo, {
          // logo: "imgs/upload/2020-05-29/711e6e65-717c-4155-ae18-1994c698050b.png"
        });
      }
    },
    SET_STARTTIME: (state, type, startTime) => {
      // type:1//new Date()
      //type:2 //null,
      //typ:3 //startTime
      if (type == 1) {
        state.startTime = new Date().getTime();
      } else if (type == 2) {
        state.startTime = null;
      } else if (type == 3) {
        state.startTime = startTime;
      } else {
        state.startTime = new Date().getTime();
      }

      localStorage.setItem("en-start-time", JSON.stringify(state.startTime));
    },
    SET_STARTTIMEGAME: (state, startTime) => {
      state.startTimeGame = startTime;
    },
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      const username = userInfo.username.trim();
      return new Promise((resolve, reject) => {
        login(username, userInfo.password, userInfo.channel)
          .then((response) => {
            const data = response.data;
            const tokenStr = data.tokenHead + data.token;
            setToken(tokenStr);
            localstorageSetToken(tokenStr);
            commit("SET_TOKEN", tokenStr);
            commit("SET_STARTTIME", 1);
            resolve(response);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },

    //  更新离线时间
    UpdateLeave({ state }) {
      if (!state.startTimeGame) {
        return;
      }
      let residue = parseInt(
        (new Date().getTime() - state.startTimeGame) / 1000 / 60
      );
      let data = {
        residue,
      };
      return new Promise((resolve, reject) => {
        updateLeave(data)
          .then((response) => {
            resolve(response);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    // 获取用户信息
    GetInfo({ commit }) {
      return new Promise((resolve, reject) => {
        getInfo()
          .then((response) => {
            const userInfo = response.data;
            commit("SET_USERINFO", userInfo);
            resolve(response);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },

    // 登出
    LogOut({ commit }) {
      return new Promise((resolve) => {
        this.dispatch("UpdateLeave");
        this.dispatch("SetTimeEnglish", 2).then(() => {
          removeToken();
          localstorageRemoveToken()
          commit("SET_TOKEN", "");
          commit("SET_USERINFO", {});
          router.push({
            name: "login",
          });
          resolve("ok");
        });
      });
    },
    // 返回在线时长
    SetTimeEnglish({ state, commit }, type, startTime) {
      return new Promise((resolve) => {
        if (!localStorage.getItem("bookData")) {
          resolve("ok");
          return;
        }
        let bookId = JSON.parse(localStorage.getItem("bookData")).book_id;
        let onlineTime = parseInt(
          (new Date().getTime() - state.startTime) / 1000
        );
        if (
          bookId &&
          state.startTime &&
          onlineTime &&
          onlineTime > 10 &&
          onlineTime < 2400
        ) {
          setTimeEnglish({
            bookId,
            onlineTime,
          }).then((res) => {
            commit("SET_STARTTIME", type, startTime);
            resolve(res);
          });
        } else {
          resolve("ok");
        }
      });
    },
    //前端 假登出
    FedLogOut({ commit }) {
      return new Promise((resolve) => {
        removeToken();
        commit("SET_TOKEN", "");
        commit("SET_USERINFO", {});
        resolve();
      });
    },
  },
};

export default user;
